<template>
  <el-dialog v-model="state.isFalse" :title="publicStore.active.name + ' - 门禁下发人员'" :before-close="onVisable" :draggable="true" width="750">
    <div class="layout-col">
      <el-form ref="formRef" :model="state.form" :rules="state.ruleList" label-width="85px">
        <el-form-item class="flex-sc" label="门禁" prop="sensor_id">
          <el-select size="large" v-model="state.form.sensor_id" placeholder="请选择" style="width:100%" clearable @change="getUserList()">
            <el-option v-for="(v, i) in state.sensorList" :key="v.id" :label="'【' + v.stationNum + '号站】' + v.name" :value="v.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="user_id">
        <div class="flex-ss h100x4 ww100 white">
          <div class="flex1 hh100 flex-col-ss mr10">
            <div class="mb5">选择人员</div>
            <div class="flex-sc ww100 plr10 bgi3">
              <span class="w70 cursor" @click="setCheckAll()">选择</span>
              <span class="flex1">已采集人员</span>
            </div>
            <div class="hh100 bo-i25-1 table">
              <div v-if="!isNull(state.userList)" 
                class="flex-sc plr10 ptb2 cursor" 
                :class="i%2 == 1?'bgi23':'bgi18'"
                @click="setCheck(v)"
                v-for="(v, i) in state.userList" :key="i">
                <span class="w70 flex-sc">
                  <span v-if="v.check == 1" class="w15 h15 rad2 f12 flex-cc p2 bgi3"><i-ep-select/></span>
                  <span v-else class="w15 h15 rad2 f12 flex-cc p2 bg-white"></span>
                </span>
                <span class="flex1">{{v.name}}</span>
              </div>
              <div class="hh100 flex-cc" v-else>暂无采集人员</div>
            </div>
          </div>
          <div class="flex1 hh100 flex-col-ss ml10">
            <div class="mb5">已下发人员</div>
            <el-scrollbar class="maxHeight ww100">
            <el-select size="large" 
            v-model="state.form.user_id" 
            placeholder="请选择" 
            style="width:100%;height:100%"
            @change="getUserNewList()" 
            multiple filterable clearable>
              <el-option v-for="(v, i) in state.userList" :key="v.id" :label="v.name" :value="v.id" />
            </el-select>
            </el-scrollbar>
          </div>
        </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" type="info" class="i23 bg-white" @click="onVisable">取 消</el-button>
        <el-button size="large" type="info" class="white bgi22" @click.stop="handleSubmit(formRef)">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import api from '../api'
  const { proxy }:any = getCurrentInstance()
  const publicStore = proxy.publicStore()
  const configStore = proxy.configStore()
  const emit = defineEmits(['init'])
  const state = reactive({
	  ...publicStore.$state,
    ruleList: {
      sensor_id: [{ required: true, message: '请选择', trigger:['blur','change'] }],
    },
    interval: null,
    sensorList: [],
    userList: [],
  })
  const props = defineProps({
    state: {
      type: [Object, Array],
      default: ()=>{return {}}
    },
  })
  let formRef = $ref()

  const onVisable = async (val) => {
    configStore.ip = ''
    state.isFalse = !state.isFalse
    if(!state.isFalse) return
    state.form = Object.assign({}, val)
    await getSensorList()
    if(!proxy.isNull(state.sensorList)){
      state.form.sensor_id = state.sensorList[0].id
      getUserList()
    }
  }

  const getUserList = async() => {
    state.userList = props.state.list.filter(a=>a.rfid_card)
    console.log('userList----', state.userList)
    state.form.user_id = await getUserId()
    console.log('form.user_id----', state.form.user_id)
    getUserNewList()
    console.log('new userList----', state.userList)
  }

  const getUserId = async() => {
    let tempArr = []
    state.userList.forEach(v => {
      if(!proxy.isNull(v.aclchan)){
        if(!proxy.isArray(v.aclchan)) v.aclchan = v.aclchan.split(',')
        if(state.form.sensor_id){
          let exist = v.aclchan.find(a=>a == state.form.sensor_id)
          if (exist) tempArr.push(v.id)
        }
      }else{
        v.aclchan = []
      }
    })
    return tempArr
  }

  const getUserNewList = async() => {
    state.userList.forEach(v => {
      let exist = state.form.user_id.find(a=>a == v.id)
      if(exist) {
        v.check = 1
      }else{
        v.check = 0
      }
    })
  }

  const setCheck = (val) => {
    val.check = val.check == 1? 0 : 1
    let index = state.form.user_id.findIndex(a=>a == val.id)
    if(index != -1){
      state.form.user_id.splice(index, 1)
    }else{
      state.form.user_id.push(val.id)
    }
  }

  const setCheckAll = () => {
    let check = state.userList.find(a=>a.check != 1)
    state.userList.forEach(v => {
      v.check = check? 1 : 0
      if(check){
        let exist = state.form.user_id.find(a=>a == v.id)
        if(!exist) state.form.user_id.push(v.id)
      }else{
        state.form.user_id = []
      }
    })
  }

  const getSensorList = async() => {
    let params = {queryApi: getQuery()}
    let res = await publicStore.post(params)
    state.sensorList = proxy.isNull(res)? [] : res.filter(a=>a.class == '0')
    // getRSensor()
  }

  const getQuery = () => {
    let queryArr = []
    if(publicStore.active.node_type == 1){
      let query = {"o": "o_sensor",	"p": [publicStore.active.id, "access_ctrl"], "i": 12}
      queryArr.push(query)
    }else{
      if(!proxy.isNull(configStore.stationList)) {
        let nodes = proxy.childrenId(configStore.stationList, publicStore.active.id, 'id')
        nodes.forEach(v => {
          let query = {"o": "o_sensor",	"p": [v, "access_ctrl"], "i": 12}
          queryArr.push(query)
        })
      }
    }
    console.log('queryArr--', queryArr)
    return queryArr
  }

  const getRSensor = async() => {
    let queryArr = []
    state.sensorList.forEach(v => {
      let query = {"o":"o_r_sensor", "p":[v.id], "i": 1}
      queryArr.push(query)
    })
    let params = {queryApi1: queryArr}
    let res = await publicStore.post(params)
    state.sensorList.forEach(v => {
      let exist = res.find(a=>a.sensor_id == v.id)
      if (exist) Object.assign(v, exist)
    })
  }

  const handleSubmit = (formEl) => {
    formEl.validate(async valid =>{
      if(proxy.isNull(state.form.sensor_id)) return ElNotification({ title: '提示', message: '请选择', type: 'error' })
      let form = Object.assign({}, state.form)
      let parmas = await getParams(form)
      console.log('开始下发----', parmas)
      configStore.ip = ''
      if(proxy.isNull(parmas.addParams.data) && proxy.isNull(parmas.delParams.batch)) return ElNotification({ title: '提示', message: '请修改信息', type: 'error' })
      if(!proxy.isNull(parmas.addParams.data)) await add(parmas.addParams, parmas.addAclchans)
      if(!proxy.isNull(parmas.delParams.batch)) await del(parmas.delParams, parmas.delAclchans)
	  }).catch((err:any) =>{
			state.loading = false
		  console.log('表单错误信息：', err);
	  })
  }

  const add = async(addParams, addAclchans) => {
    // let node = proxy.parentNodes(publicStore._public.tree, state.form.sensor_id, 'id')
    // let sensor = node.filter(a=>a.class == 2)
    // if (!proxy.isNull(sensor) && !proxy.isNull(sensor[0].localSvcIP)) configStore.ip = sensor[0].localSvcIP + ':8808'
    api.aclhanAdd(addParams).then((res:any) => {
      if(res.errorCode == 200){
        ElNotification({ title: '提示', message: '下发人员成功', type: 'success' })
        setUserAdd(addAclchans)
      }else{
        configStore.ip = ''
        ElNotification({ title: '提示', message: res.errorMessage, type: 'error' })
      }
    }).catch((err) => {
      ElNotification({ title: '提示', message: '操作失败', type: 'error' })
    })
  }

  const setUserAdd = async(addAclchans) => {
    configStore.ip = ''
    if(proxy.isNull(addAclchans)) return
    api.updateApi(addAclchans).then((res:any) => {
      if(res.errcode == 0){
        ElNotification({ title: '提示', message: '更新成功', type: 'success' })
        onVisable()
        emit('init')
      }else{
        configStore.ip = ''
      }
    }).catch((err) => {
      configStore.ip = ''
      ElNotification({ title: '提示', message: '操作失败', type: 'error' })
    })
  }

  const del = async(delParams, delAclchans) => {
    // let node = proxy.parentNodes(publicStore._public.tree, state.form.sensor_id, 'id')
    // let sensor = node.filter(a=>a.class == 2)
    // if (!proxy.isNull(sensor) && !proxy.isNull(sensor[0].localSvcIP)) configStore.ip = sensor[0].localSvcIP + ':8808'
    api.aclhanDel(delParams).then((res:any) => {
      if(res.errorCode == 200){
        ElNotification({ title: '提示', message: '删除下发人员成功', type: 'success' })
        setUserAdd(delAclchans)
      }else{
        configStore.ip = ''
        ElNotification({ title: '提示', message: res.errorMessage, type: 'error' })
      }
    }).catch((err) => {
      configStore.ip = ''
      ElNotification({ title: '提示', message: '操作失败', type: 'error' })
    })
  }

  const getParams = async(form) => {
    console.log('form----', form)
    let userIds = await getUserId()
    console.log('userIds----', userIds)
    // 添加人员到门禁
    let addId = []
    let addIds = []
    form.user_id.forEach(v => {
      let exist = userIds.find(a=>a == v)
      if(!exist) addId.push(v)
      addIds.push(v)
    })
    console.log('addId----', addId)
    let addAclchans = []
    let addQuery = []
    let addParams = {sensorId: form.sensor_id, data: addQuery}
    addIds.forEach(v => {
      let exist = state.userList.find(a=>a.id == v)
      if(exist) {
        let query = {cardNo: exist.rfid_card, userId: exist.id, userName: exist.name, humanFaceBase64: exist.face_image, fingers: exist.finger_print.split(",")}
        addQuery.push(query)
      }           
    }) 
    addId.forEach(v => {
      let exist = state.userList.find(a=>a.id == v)
      if(exist) {
        let aclchan = exist.aclchan.concat([form.sensor_id])
        let addAclchan = {o: "o_comm_usr", t:"upd", a: "修改", id: exist.id, aclchan: aclchan.join()}
        addAclchans.push(addAclchan)
      }           
    }) 
    console.log('addParams', addParams)
    // 删除人员从门禁
    let delId = []
    userIds.forEach(v => {
      let exist = form.user_id.find(a=>a == v)
      if(!exist) delId.push(v)
    })
    console.log('delId----', delId)
    let delAclchans = []
    let delQuery = []
    let delParams = {batch: delQuery}
    delId.forEach(v => {
      let exist = state.userList.find(a=>a.id == v)
      if(exist) {
        let query = {sensorId: form.sensor_id, cardNo: exist.rfid_card, userId: exist.id}
        delQuery.push(query)
        let index = exist.aclchan.findIndex(a=>a == form.sensor_id)
        exist.aclchan.splice(index, 1)
        let delAclchan = {o: "o_comm_usr", t:"upd", a: "修改", id: exist.id, aclchan: exist.aclchan.join()}
        delAclchans.push(delAclchan)
      }           
    })
    console.log('delParams', delParams)
    return {addParams: addParams, delParams: delParams, addAclchans: addAclchans, delAclchans: delAclchans}
  }
 
  // 暴露给父组件
  defineExpose({
    onVisable
  })
</script>

<style scoped lang="scss">
.maxHeight{
  max-height: 400px;
}
:deep(.el-select .el-select-tags-wrapper.has-prefix){
  display: flex !important;
  flex-direction: column !important;
  flex-wrap: wrap !important;
}
:deep(.el-select__tags .el-tag){
  margin: 5px 5px 5px 0;
}
</style>
